<?php
// +----------------------------------------------------------------------
// | 角色控制器
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\admin\service\SysRoleService;
use app\admin\service\SysMenuService;
use app\common\enum\ErrorEnum;
use think\facade\View;
use app\common\enum\BaseStatusEnum;

class SysRole extends AdminController
{   
    // 首页
    public function index(){
        $res = SysRoleService::page($this->request->get(), ['order' => ['sort' => 'desc', 'id' => 'desc']]);

        $data = [
            'list' => $res, 
            'page' => $res->render(),
            'statusList' => BaseStatusEnum::getAll(),
            'params' => $this->request->get(),
            'menuList' => flattenMenuArray(session("menuList"))
        ];

        return View::fetch('', $data);
    }

    // 新增
    public function add(){
        $data = $this->request->post();
        //验证规则
        $validate = [
            'role_name' => 'require',
        ];
        //提示信息
        $message = [
            'role_name.require' => '角色名不能为空!',
        ];
        $this->validate($data, $validate, $message);
        return success(SysRoleService::save($data));
    }

    // 更新
    public function edit(){
        $data = $this->request->post();
        //验证规则
        $validate = [
            'id' => 'require',
            'role_name' => 'require',
        ];
        //提示信息
        $message = [
            'id.require' => 'ID不能为空!',
            'role_name.require' => '角色名不能为空!',
        ];

        $this->validate($data, $validate, $message);

        return success(SysRoleService::update($data));
    }

    // 详情
    public function info() {
        $id = $this->request->get("id");
        if (empty($id)) {
            return success();
        }
        return success(SysRoleService::info($id));
    }

    // 删除
    public function delete(){
        $ids = $this->request->get("ids");
        if(empty($ids)){
            return failure(ErrorEnum::SELECT_DELETE_DATA_CODE, ErrorEnum::SELECT_DELETE_DATA_DESC);
        }

        SysRoleService::destroy($ids);
        return success();
    }

    // 授权
    public function authorize() {
        $data = $this->request->post();
        $validate = [
            'id' => 'require',
            'menus' => 'require',
        ];
        $message = [
            'id.require' => '角色ID不能为空!',
            'menus.require' => '请选择需要分配的菜单权限!',
        ];
        $this->validate($data, $validate, $message);

        return success(SysRoleService::authorize($data));
    }

    // 获取角色拥有的菜单权限
    public function permissions() {
        $id = $this->request->get("id");
        if (empty($id)) {
            return success();
        }
        return success(SysRoleService::getPermissions([$id]));
    }

}
